package uva;

import java.util.ArrayList;

import rice.pastry.NodeHandle;
import rice.pastry.PastryNode;
import rice.pastry.routing.RouteSet;
import rice.pastry.routing.RoutingTable;

public class MaliciousNodes extends ArrayList<rice.pastry.NodeHandle> {

	private static MaliciousNodes _instance;

	private boolean areMaliciousNodesActive;

	private MaliciousNodes() {
		areMaliciousNodesActive = false;
	}

	public static MaliciousNodes getInstance() {
		if (_instance == null) {
			_instance = new MaliciousNodes();

		}

		return _instance;
	}

	public int countMaliciousNodes(RouteSet[] row, boolean logForIvan) {
		if(!logForIvan){
			return -1;
		}
		int count = 0;

		for (int i = 0; i < row.length; i++) {

			if (row != null && row[i] != null && row[i].get(0) != null && MaliciousNodes.getInstance().isPresent(row[i].get(0).getId())) {
				count++;
				System.out.println("row has malicious node: >!" + row[i].get(0).getId().toStringFull() + "!<");
			}
		}

		return count;
	}

	public int countMaliciousNodes(PastryNode node, boolean logForIvan) {
		if(!logForIvan){
			return -1;
		}
		int count = 0;
		if (MaliciousNodes.getInstance().isPresent(node.getId())) {
			System.out.println("node " + node.getId() + " is malicious, skipping count");
			return -1;
		}
		RoutingTable table = node.getRoutingTable();
		for (int i = 0; i < table.numRows(); i++) {
			for (int j = 0; j < table.numColumns(); j++) {

				if (table.getRow(i)[j] != null && table.getRow(i)[j].get(0) != null && MaliciousNodes.getInstance().isPresent(table.getRow(i)[j].get(0).getId())) {
					count++;
					//System.out.println("node: " + node.getId().toStringFull() + " has a malicious node: >!" + table.getRow(i)[j].get(0).getId().toStringFull() + "!<");
				}
			}
		}

		System.out.println("node: " + node.getId().toStringFull() + " had " + count + " malicious nodes");
		return count;
	}
	
	public boolean isPresent(String id) {

		for (int i = 0; i < this.size(); i++) {
			String evilIdString = this.get(i).getId().toStringFull();
			if (id.contains(evilIdString)) {
				return true;
			}
		}
		return false;
	}

	public boolean isPresent(rice.p2p.commonapi.Id id) {

		for (int i = 0; i < this.size(); i++) {
			String evilIdString = this.get(i).getId().toStringFull();
			if (id.toStringFull().contains(evilIdString)) {
				return true;
			}
		}
		return false;
	}

	public boolean getAreMaliciousNodesActive() {
		return areMaliciousNodesActive;
	}

	public void setAreMaliciousNodesActive(boolean areMaliciousNodesActive) {
		this.areMaliciousNodesActive = areMaliciousNodesActive;
	}
}
